﻿using System.Collections.Generic;
using HMIS.FrameWork.DomainBase;
using HMIS.FrameWork.Repository.Nhb;
using HMIS.Infrastructure.Core.Authority;

namespace HMIS.Infrastructure.Core.Repositories.Impl
{
	public class UserRoleDepRepositoryImpl : RepositoryNhbImpl<UserRoleDep>, IUserRoleDepRepository
	{
		#region IHospUserRepository 成员

		public IList<UserRoleDep> GetExists(string userId, string roleId, string deptId)
		{
			string sqlStr = @"select t from UserRoleDep t 
								where t.Person.Id = :userId 
									and t.Role.Id = :roleId
									and t.Department.Id = :deptId";
			var q = Session.CreateQuery(sqlStr)
				.SetString("userId", userId)
				.SetString("roleId", roleId)
				.SetString("deptId", deptId);
			return q.List<UserRoleDep>();
		}

		public IList<object[]> QueryUserListByCode(string query, 
			string userCode, 
			string roleCode, 
			string deptCode, 
			int start, 
			int limit, 
			string sort, 
			string dir, 
			List<DataFilter> filters, out long total)
		{
			// filter
			var strFilter = base.GetHqlstrByExtFilter(filters, "t");
			// 排序
			string ordStr = string.IsNullOrEmpty(sort) ? string.Empty : " order by t." + sort + " " + dir;
			// sql条件
			string sqlStr = @" from UserRoleDep as t
								left join t.Person p
								left join t.Role r
								left join t.Department d
								where p.InputCode1 like (:query)
									and p.State = :PersonState 
									and r.IsDelete = 0"
				+ (string.IsNullOrEmpty(userCode) ? string.Empty : " and p.Code = :usercode ")
				+ (string.IsNullOrEmpty(roleCode) ? string.Empty : " and r.Code = :rolecode ")
				+ (string.IsNullOrEmpty(deptCode) ? string.Empty : " and d.Code = :deptcode ")
				+ (string.IsNullOrEmpty(strFilter) ? string.Empty : " and " + strFilter);

			var q = Session.CreateQuery(@"select p.Id, p.LoginName, p.Name, r.Id, r.Code, r.Name, t.Id, d.Id, d.Code, d.Name " + sqlStr + ordStr)
				.SetString("query", query + "%")
				.SetEnum("PersonState", PersonState.Normal);

			// 汇总查询
			var q_total = Session.CreateQuery(@"select count(*) " + sqlStr)
				.SetString("query", query + "%")
				.SetEnum("PersonState", PersonState.Normal);

			//设置条件
			if (!string.IsNullOrEmpty(userCode))
			{
				q.SetString("usercode", userCode);
				q_total.SetString("usercode", userCode);
			}
			if (!string.IsNullOrEmpty(roleCode)){
				q.SetString("rolecode", roleCode);
				q_total.SetString("rolecode", roleCode);
			}
			if (!string.IsNullOrEmpty(deptCode))
			{
				q.SetString("deptcode", deptCode);
				q_total.SetString("deptcode", deptCode);
			}

			// 设置结果集
			if (limit > 0)
				q.SetFirstResult(start).SetMaxResults(limit);

			total = q_total.UniqueResult<long>();
			return q.List<object[]>();
		}

		#endregion
	}
}
